<template>
  <div class="container">
    <div class="left-board">
      <div class="knowledge-header">
        <el-input
          v-model="newKbName"
          placeholder="请输入知识库名称"
          class="kb-input"
          size="small"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          class="kb-create-btn"
          @click="createKnowledgeBase"
        >
          新建
        </el-button>
      </div>

      <el-scrollbar class="left-scrollbar">
        <div class="knowledge-list">
          <div
            v-for="knowledge in knowledgelist"
            :key="knowledge.kb_id"
            class="knowledge-item"
            :class="{ 'active': selectedKnowledgeId === knowledge.kb_id }"
            @click="selectKnowledge(knowledge)"
          >
            <div
              class="action-trigger"
              @mouseenter="showMenu(knowledge.kb_id)"
              @mouseleave="hideMenu(knowledge.kb_id)"
            >
              <div class="knowledge-name">
                {{ knowledge.kb_name }}
              </div>

              <div
                class="action-menu"
                v-if="showMenuId === knowledge.kb_id"
                @mouseenter="showMenu(knowledge.kb_id)"
                @mouseleave="hideMenu(knowledge.kb_id)"
              >
                <div class="menu-arrow"></div>
                <div class="menu-item" @click="renameKnowledge(knowledge.kb_id)">
                  <i class="el-icon-edit"></i> 重命名
                </div>
                <div class="menu-item" @click="deleteKnowledge(knowledge.kb_id)">
                  <i class="el-icon-delete"></i> 删除
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board">
      <el-scrollbar class="center-scrollbar">
        <div class="top-bar">
          <div class="knowledge-info">
            <span class="info-label">{{ selectedKnowledgeName }}: </span>
            <span class="info-value">知识库ID: {{ selectedKnowledgeId || '-' }}</span>
          </div>
        </div>

        <!-- 文档类型标签和操作按钮 -->
        <div class="doc-toolbar">
          <el-tabs v-model="activeDocTab" type="card" size="small" class="doc-tabs" @tab-click="handleTabClick">
            <el-tab-pane label="文档集" name="documents"></el-tab-pane>
            <el-tab-pane label="问答集" name="qa"></el-tab-pane>
          </el-tabs>

          <div class="action-buttons">
            <el-button
              v-if="activeDocTab === 'documents'"
              type="primary"
              size="small"
              class="upload-btn"
              @click="openUploadDialog"
            >
              上传文档
            </el-button>
            <el-button
              v-if="activeDocTab === 'qa'"
              type="primary"
              size="small"
              class="qna-btn"
              @click="openQnaDialog"
            >
              录入问答
            </el-button>
          </div>
        </div>

        <!-- 文档集内容 -->
        <div v-if="activeDocTab === 'documents'" class="doc-table-container">
          <el-table
            :data="documentList"
            stripe
            key="1"
            size="small"
            class="doc-table"
            v-loading="tableLoading"
          >
            <el-table-column prop="file_id" label="文档ID" width="240"></el-table-column>
            <el-table-column prop="file_name" label="文档名称" min-width="180"></el-table-column>
            <el-table-column label="文档状态" width="120">
              <template slot-scope="scope">
                <div class="status-container">
                  <i v-if="scope.row.status === 'green'" class="el-icon-success" style="color: #52c41a"></i>
                  <i v-else-if="scope.row.status === 'gray' || scope.row.status === 'yellow'" class="el-icon-loading" style="color: #07a7ec"></i>
                  <i v-else class="el-icon-error" style="color: #f51a2d"></i>
                  <span :class="scope.row.status === 'green'?'status-text': scope.row.status === 'gray'?'status-text-info':'status-text-fail'">
                    {{ scope.row.status === 'green' ? '解析成功' : scope.row.status === 'gray' || scope.row.status === 'yellow' ? '解析中' : '解析失败' }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="bytes" label="文件大小" width="90">
              <template slot-scope="scope">
                {{ formatBytes(scope.row.bytes) }}
              </template>
            </el-table-column>
            <el-table-column prop="content_length" label="解析后字符数" width="110"></el-table-column>
            <el-table-column prop="timestamp" label="创建日期" width="120"></el-table-column>
            <el-table-column prop="msg" label="备注" min-width="80">
              <template slot-scope="scope">
                <el-tooltip class="item" :content="scope.row.msg" placement="top">
                  <div>{{ formatRemark(scope.row.msg) }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="170" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  style="color: red"
                  @click="deleteDocument(scope.row)"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-monitor"
                  @click="previewDocument(scope.row)"
                  :disabled="scope.row.status=='red'"
                >预览</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="loadDocuments"
          />
        </div>

        <!-- 问答集内容 -->
        <div v-if="activeDocTab === 'qa'" class="qa-container">
          <el-table
            :data="qaList"
            stripe
            key="2"
            size="small"
            class="qa-table"
            v-loading="qaLoading"
          >
            <el-table-column prop="file_id" label="ID" width="240"></el-table-column>
            <el-table-column prop="file_name" label="问题" min-width="200">
              <template slot-scope="scope">
                <el-tooltip class="item" :content="scope.row.question" placement="top">
                  <div>{{ scope.row.question }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="answer" label="答案" min-width="160"></el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <div class="status-container">
                  <i v-if="scope.row.status === 'green'" class="el-icon-success" style="color: #52c41a"></i>
                  <i v-else-if="scope.row.status === 'gray'" class="el-icon-loading" style="color: #07a7ec"></i>
                  <i v-else class="el-icon-error" style="color: #f51a2d"></i>
                  <span :class="scope.row.status === 'green'?'status-text': scope.row.status === 'gray'?'status-text-info':'status-text-fail'">
                    {{ scope.row.status === 'green' ? '学习完成' : (scope.row.status === 'gray' || scope.row.status === 'yellow') ? '上传中' : '上传失败' }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="content_length" label="字符数" width="90"></el-table-column>
            <el-table-column prop="timestamp" label="创建日期" width="120"></el-table-column>
            <el-table-column label="操作" width="170" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="editQA(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  style="color: red"
                  @click="deleteQA(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total2>0"
            :total="total2"
            :page.sync="queryParams2.pageNum"
            :limit.sync="queryParams2.pageSize"
            @pagination="loadQAs"
          />
        </div>

        <el-dialog
          title="上传文档"
          :visible.sync="uploadDialogVisible"
          width="30%">
          <div class="upload-container">
            <!-- 拖拽上传区域 -->
            <el-upload
              ref="uploadRef"
              class="upload-dragger"
              drag
              :action="uploadUrl"
              :headers="uploadHeaders"
              :data="{ kb_id: selectedKnowledgeId }"
              :file-list="fileList"
              :multiple="true"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-progress="handleUploadProgress">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="upload-tip">
                <p>支持文件格式：md, txt, pdf, jpg, png, jpeg, docx, xlsx, pptx, eml, csv</p>
                <p>单个文档小于30M，单张图片小于5M，文件总大小不得超过125M</p>
              </div>
            </el-upload>

            <!-- 上传进度条 -->
            <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
              <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitUpload"
              :loading="uploadLoading"
              :disabled="uploadFileList.length === 0"
            >
              确定上传
            </el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="录入问答"
          :visible.sync="qnaDialogVisible"
          width="30%">
          <el-tabs v-model="qnaActiveName" @tab-click="handleTabClick2" style="margin-top: -20px" class="custom-tabs">
            <el-tab-pane label="输入问答" name="输入问答">
              <el-form ref="form" :model="form" :rules="rules" label-width="1px" style="width: 90%;margin-left: 5%">
                <el-form-item label="" prop="question">
                  <el-input
                    v-model="form.question"
                    placeholder="请输入问题，100字符以内"
                    maxlength="100"
                    show-word-limit>
                  </el-input>
                </el-form-item>
                <el-form-item label="" prop="answer">
                  <el-input
                    v-model="form.answer"
                    type="textarea"
                    :rows="5"
                    maxlength="1000"
                    show-word-limit
                    placeholder="请输入答案，1000字符以内">
                  </el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="批量上传" name="批量上传">
              <div class="upload-container">
                <span class="downQna-text" @click="downQna">下载模板</span>
                <span>(完成填写后再上传，问题总数不超过500条)</span>
                <!-- 拖拽上传区域 -->
                <el-upload
                  ref="uploadRef"
                  class="upload-dragger"
                  style="margin-top: 15px"
                  drag
                  :action="uploadFaqUrl"
                  :headers="uploadHeaders"
                  :data="{ kb_id: selectedKnowledgeId+'_FAQ' }"
                  :multiple="true"
                  :before-upload="beforeUpload2"
                  :on-success="handleUploadSuccess2">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </div>
            </el-tab-pane>
          </el-tabs>

          <span slot="footer" class="dialog-footer" v-if="qnaActiveName=='输入问答'">
            <el-button @click="qnaDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitQna">确 定</el-button>
          </span>
        </el-dialog>
      </el-scrollbar>
    </div>
    <docDetails ref="documentDetail" v-bind:selectedKnowledgeId="selectedKnowledgeId"></docDetails>
  </div>
</template>

<script>
import { list, addKb, delKb, updateKb } from '@/api/knowledgemanagement/index'
import { doclist, delDoc } from "@/api/knowledgemanagement/document";
import { qnalist, addFaq ,updateFaq ,delFaq,downFaq } from "@/api/knowledgemanagement/qna";
import docDetails from './modules/docDetails'

export default {
  components: { docDetails },
  data() {
    return {
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total2: 0,
      queryParams2: {
        pageNum: 1,
        pageSize: 10
      },
      knowledgelist: [],
      documentList: [],
      qaList: [], // 问答集数据
      activeDocTab: 'documents',
      qnaActiveName: '输入问答',
      selectedKnowledgeId: '',
      selectedKnowledgeName: '',
      showMenuId: null,
      newKbName: '',
      tableLoading: false,
      qaLoading: false, // 问答集加载状态

      uploadDialogVisible: false, // 上传对话框显示状态
      uploadFileList: [], // 待上传文件列表
      uploadUrl: process.env.VUE_APP_BASE_API + '/document/uploadDoc', // 后端上传接口
      uploadFaqUrl: process.env.VUE_APP_BASE_API + '/qna/batchAddFaq', // 后端上传接口
      uploadHeaders: {
        'Authorization': ""
      },
      uploadProgress: 0, // 上传进度
      uploadStatus: 'normal', // 上传状态：normal/success/exception
      uploadLoading: false, // 上传按钮加载状态
      uploadTotalSize: 0, // 总文件大小
      maxTotalSize: 125 * 1024 * 1024, // 总大小限制(125M)
      maxFileSize: 30 * 1024 * 1024, // 单个文件限制(30M)
      maxImageSize: 5 * 1024 * 1024, // 图片文件限制(5M)
      allowedTypes: ['md', 'txt', 'pdf', 'jpg', 'png', 'jpeg', 'docx', 'xlsx', 'pptx', 'eml', 'csv'], // 允许的文件类型
      allowedTypes2: ['xlsx'], // 允许的文件类型
      qnaDialogVisible: false, // 录入问答对话框显示状态
      form:{
        file_id:'',
        answer:'',
        question:'',
      },
      rules: {
        answer: [
          { required: true, message: '请输入问题', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
      },
      fileList:[],
    }
  },
  created() {
    this.init();
  },
  methods: {
    getCookie(name) {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // 查找以目标名称开头的Cookie（格式："name=value"）
        if (cookie.startsWith(`${name}=`)) {
          return cookie.substring(name.length + 1); // 返回值部分
        }
      }
      return null; // 未找到返回null
    },

    // 获取认证令牌（从Cookie中）
    getAuthToken() {
      const token = this.getCookie('Admin-Token'); // 键名与Cookie名称一致
      return token ? `Bearer ${token}` : ''; // 拼接Bearer前缀
    },
    //上传文档
    openUploadDialog() {
      if (!this.selectedKnowledgeId) {
        this.$message.warning('请先选择一个知识库');
        return;
      }
      // 从Cookie中获取Admin-Token并设置请求头
      const token = this.getAuthToken();
      if (!token) {
        this.$message.error('未找到登录令牌，请重新登录');
        return;
      }

      this.uploadHeaders.Authorization = token; // 更新请求头
      this.uploadDialogVisible = true;
      this.uploadFileList = []; // 重置文件列表
      this.uploadProgress = 0; // 重置进度
    },
    openQnaDialog(){
      if (!this.selectedKnowledgeId) {
        this.$message.warning('请先选择一个知识库');
        return;
      }
      // 从Cookie中获取Admin-Token并设置请求头
      const token = this.getAuthToken();
      if (!token) {
        this.$message.error('未找到登录令牌，请重新登录');
        return;
      }
      this.uploadHeaders.Authorization = token; // 更新请求头
      this.form = Object.assign({})
      this.qnaDialogVisible = true;
    },
    // 关闭对话框时清空文件列表
    handleDialogClose() {
      this.uploadFileList = [];
      this.uploadProgress = 0;
    },
    // 文件上传前验证
    beforeUpload(file) {
      // 1. 验证文件类型
      const fileExt = file.name.split('.').pop().toLowerCase();
      if (!this.allowedTypes.includes(fileExt)) {
        this.$message.error(`不支持的文件格式: ${fileExt}，请上传支持的格式`);
        return false;
      }

      // 2. 验证文件大小
      const isImage = ['jpg', 'png', 'jpeg'].includes(fileExt);
      const maxSize = isImage ? this.maxImageSize : this.maxFileSize;

      if (file.size > maxSize) {
        const sizeText = isImage ? '5M' : '30M';
        this.$message.error(`单个${isImage ? '图片' : '文档'}大小不能超过${sizeText}`);
        return false;
      }

      // 3. 验证总大小
      this.uploadTotalSize += file.size;
      if (this.uploadTotalSize > this.maxTotalSize) {
        this.$message.error('文件总大小不能超过125M');
        this.uploadTotalSize -= file.size; // 恢复总大小
        return false;
      }

      return true; // 验证通过，允许上传
    },
    beforeUpload2(file) {
      // 1. 验证文件类型
      const fileExt = file.name.split('.').pop().toLowerCase();
      if (!this.allowedTypes2.includes(fileExt)) {
        this.$message.error(`不支持的文件格式: ${fileExt}，请下载模板后填写上传`);
        return false;
      }
      return true; // 验证通过，允许上传
    },
    // 文件数量超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择多个文件，已自动忽略多余文件`);
    },
    // 提交上传
    submitUpload() {
      if (this.uploadFileList.length === 0) return;
      const token = this.getAuthToken();
      if (!token) {
        this.$message.error('令牌已过期，请重新登录');
        this.uploadDialogVisible = false;
        return;
      }
      this.uploadHeaders.Authorization = token; // 确保令牌是最新的
      this.uploadLoading = true;
      // 获取上传组件实例并手动上传
      const uploadComponent = this.$refs.uploadRef;
      uploadComponent.submit();
    },
    // 上传进度处理
    handleUploadProgress(event, file, fileList) {
      // 计算总体进度(简单平均计算，实际可根据文件大小加权)
      const totalProgress = fileList.reduce((sum , item) => sum + (item.percentage || 0), 0) / fileList.length;
      this.uploadProgress = Math.floor(totalProgress);
    },
    // 上传成功处理
    handleUploadSuccess(response, file, fileList) {
      // 检查是否所有文件都上传完成
      const allSuccess = fileList.every(item => item.status === 'success');
      if (allSuccess) {
        this.$message.success('所有文件上传成功');
        this.uploadDialogVisible = false;
        this.uploadLoading = false;
        this.uploadFileList = []; // 清空列表
        this.fileList = []
        this.loadDocuments(); // 重新加载文档列表

        setTimeout(() => {
          this.loadDocuments(); // 重新加载文档列表
        }, 5000);

        setTimeout(() => {
          this.loadDocuments(); // 重新加载文档列表
        }, 10000);
      }
    },
    handleUploadSuccess2(response, file, fileList) {
      // 检查是否所有文件都上传完成
      const allSuccess = fileList.every(item => item.status === 'success');
      if (allSuccess) {
        this.$message.success('所有文件上传成功');
        this.qnaDialogVisible = false;
        this.loadQAs(); // 重新加载文档列表

        setTimeout(() => {
          this.loadQAs(); // 重新加载文档列表
        }, 3000);
      }
    },
    // 上传失败处理
    handleUploadError(err, file, fileList) {
      this.$message.error(`文件 ${file.name} 上传失败，请重试`);
      this.uploadLoading = false;
      this.uploadStatus = 'exception';
    },
    init() {
      list().then(response => {
        this.knowledgelist = response.data;
        if (this.knowledgelist.length > 0) {
          this.selectedKnowledgeId = this.knowledgelist[0].kb_id;
          this.selectedKnowledgeName = this.knowledgelist[0].kb_name;
          this.loadContentByTab(); // 初始化时加载对应标签内容
        }
      })
    },

    // 根据活动标签加载内容
    loadContentByTab() {
      if (!this.selectedKnowledgeId) return;

      if (this.activeDocTab === 'documents') {
        this.loadDocuments();
      } else if (this.activeDocTab === 'qa') {
        this.loadQAs();
      }
    },

    // 加载文档集
    loadDocuments() {
      this.tableLoading = true;
      doclist({
        "kb_id": this.selectedKnowledgeId,
        "page_id": this.queryParams.pageNum,
        "page_limit": this.queryParams.pageSize,
        "user_id": "zzp"
      }).then(res => {
        this.documentList = res.data.details || [];
        this.total = res.data.total;
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false;
      });
    },

    // 加载问答集
    loadQAs() {
      this.qaLoading = true;
      qnalist({
        "kb_id": this.selectedKnowledgeId,
        "page_id": this.queryParams2.pageNum,
        "page_limit": this.queryParams2.pageSize
      }).then(res => {
        this.qaList = res.data.details || [];
        this.total2 = res.data.total;
        this.qaLoading = false;
      }).catch(() => {
        this.qaLoading = false;
      });
    },

    // 选择知识库
    selectKnowledge(value) {
      this.selectedKnowledgeId = value.kb_id;
      this.selectedKnowledgeName = value.kb_name;
      this.loadContentByTab(); // 切换知识库时加载内容
      this.showMenuId = null;
    },

    // 标签切换处理
    handleTabClick() {
      this.loadContentByTab();
    },
    handleTabClick2() {

    },

    // 显示/隐藏菜单
    showMenu(kbId) {
      this.showMenuId = kbId;
    },
    hideMenu(kbId) {
      setTimeout(() => {
        if (this.showMenuId === kbId) {
          this.showMenuId = null;
        }
      }, 200);
    },

    // 重命名知识库
    renameKnowledge(id) {
      const knowledge = this.knowledgelist.find(kb => kb.kb_id === id);
      if (!knowledge) return;

      this.$prompt(`重命名知识库 "${knowledge.kb_name}"`, '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: knowledge.kb_name
      }).then(({ value }) => {
        updateKb({
          "kb_id": id,
          "kb_name": value
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('知识库重命名成功');
            this.init();
          } else {
            this.$message.error('重命名失败，请稍后再试');
          }
        }).catch(() => {
          this.$message.error('重命名失败，请稍后再试');
        })
      }).catch(() => {
        this.$message.info('取消重命名');
      });
    },

    // 删除知识库
    deleteKnowledge(id) {
      const knowledge = this.knowledgelist.find(kb => kb.kb_id === id);
      if (!knowledge) return;

      this.$confirm(`确定要删除知识库 "${knowledge.kb_name}" 吗?`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delKb({ kb_id: id }).then(res => {
          if (res.code === 200) {
            this.$message.success('知识库删除成功');
            this.init();
          } else {
            this.$message.error('知识库删除失败');
          }
        })
      }).catch(() => {
        this.$message.info('取消删除');
      });
    },

    // 创建知识库
    createKnowledgeBase() {
      if (!this.newKbName.trim()) {
        this.$message.warning('请输入知识库名称');
        return;
      }
      addKb({ kb_name: this.newKbName }).then(res => {
        if (res.code === 200) {
          this.$message.success('知识库创建成功');
          this.init();
          this.newKbName = '';
        } else {
          this.$message.error('知识库创建失败');
          this.newKbName = '';
        }
      })
    },

    // 格式化备注信息
    formatRemark(remark) {
      if (!remark) return '';
      return remark.length > 30 ? `${remark.slice(0, 30)}...` : remark;
    },
    //根据字节计算文件大小
    formatBytes(bytes){
      if(bytes <= 1024*1024){
        return (bytes/1024).toFixed(2) + 'KB'
      }else{
        return (bytes/(1024*1024)).toFixed(2) + 'MB'
      }
    },

    // 文档操作
    deleteDocument(row) {
      this.$confirm('确定要删除此文档吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        delDoc({file_id:row.file_id,kb_id:this.selectedKnowledgeId}).then(res => {
          this.$message.success('删除成功');
          this.loadDocuments()
        }).catch(() => {
          this.tableLoading = false;
        });
      }).catch(() => {
        this.$message.info('取消删除');
      });
    },
    previewDocument(row) {
      this.$refs.documentDetail.open(row);
    },

    // 问答操作
    editQA(row) {
      this.qnaDialogVisible = true
      this.form = Object.assign({}, row);
    },
    deleteQA(row) {
      this.$confirm('确定要删除此文档吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.qaLoading = true;
        delFaq({file_id:row.file_id,kb_id:this.selectedKnowledgeId + '_FAQ'}).then(res => {
          this.$message.success('删除成功');
          this.loadQAs()
        }).catch(() => {
          this.qaLoading = false;
        });
      }).catch(() => {
        this.$message.info('取消删除');
      });
    },
    submitQna(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if(this.form.file_id!='' && this.form.file_id!=null){
            //编辑
            updateFaq({
              "kb_id": this.selectedKnowledgeId + '_FAQ',
              "file_ids": this.form.file_id,
              "question": this.form.question,
              "answer": this.form.answer
            }).then(res => {
              this.qnaDialogVisible = false
              this.loadQAs()
              setTimeout(() => {
                this.loadQAs(); // 重新加载文档列表
              }, 3000);
            })
          }else{
            //新增
            addFaq({
              "kb_id": this.selectedKnowledgeId + '_FAQ',
              "question": this.form.question,
              "answer": this.form.answer
            }).then(res => {
              this.qnaDialogVisible = false
              this.form.file_ids=''
              this.loadQAs()
              setTimeout(() => {
                this.loadQAs(); // 重新加载文档列表
              }, 3000);
            })
          }
        }
      })
    },
    downQna(){
      downFaq().then(data =>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), '问答录入模板.xlsx')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '问答录入模板.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    }
  }
}
</script>

<style lang='scss'>
.knowledge-header {
  padding: 12px 10px;
  display: flex;
  gap: 8px;
}

body, html{
  margin: 0;
  padding: 0;
  background: #fff;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
}

input, textarea{
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
}

.left-scrollbar .el-scrollbar__wrap {
  box-sizing: border-box;
  overflow-x: hidden !important;
  margin-bottom: 0 !important;
}

.container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.left-board {
  width: 260px;
  position: absolute;
  left: 0;
  top: 0;
  height: 100vh;
  border-right: 1px solid #f1e8e8;
}

.left-scrollbar{
  height: calc(100vh - 42px);
  overflow: hidden;
}

.knowledge-list {
  padding: 10px;
}

.knowledge-item {
  position: relative;
  height: 42px;
  line-height: 40px;
  padding: 8px 15px;
  margin-bottom: 5px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;

  &.active {
    background-color: #9b59b6;
    color: white;
  }

  &:hover:not(.active) {
    background-color: #f5f5f5;
  }
}

.knowledge-name {
  position: relative;
  padding-right: 100px;
  height: 24px;
  line-height: 24px;
}

/* 悬浮菜单 */
.action-menu {
  position: absolute;
  right: 35px;
  top: 50%;
  transform: translateY(-50%);
  width: 150px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.menu-arrow {
  position: absolute;
  right: -6px;
  top: 15px;
  width: 12px;
  height: 12px;
  background-color: #fff;
  transform: rotate(45deg);
  border-right: 1px solid #ebeef5;
  border-top: 1px solid #ebeef5;
}

.menu-item {
  height: 36px;
  line-height: 36px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  color: #606266;

  &:hover {
    background-color: #f5f5f5;
  }

  i {
    color: #909399;
    width: 16px;
    text-align: center;
  }
}

.center-board {
  height: 100vh;
  width: auto;
  margin: 0 0 0 260px;
  box-sizing: border-box;
}

.center-scrollbar {
  height: 100vh;
  overflow: hidden;
}

.top-bar {
  padding: 12px 15px;
  border-bottom: 1px solid #f1e8e8;
}

.knowledge-info {
  color: #606266;
  font-size: 14px;
}

.info-label {
  margin-right: 10px;
  color: #303133;
  font-weight: normal;
}

.doc-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f1e8e8;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 文档集样式 */
.doc-table-container {
  padding: 15px;
}

.doc-table {
  width: 100%;
}

/* 问答集样式 */
.qa-container {
  padding: 15px;
}

.qa-table {
  width: 100%;
}

.question-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 空状态样式 */
.empty-state {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  margin-top: 10px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.empty-text {
  font-size: 14px;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-text {
  font-size: 12px;
  color: #52c41a;
}

.status-text-info {
  font-size: 12px;
  color: #07a7ec;
}

.status-text-fail {
  font-size: 12px;
  color: #f51a2d;
}

.operation-buttons {
  text-align: center;
  display: flex;
  gap: 10px;
  font-size: 12px;
}

.remark-tooltip {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 问答集按钮样式 */
.record-faq-btn {
  background-color: #673ab7;
  border-color: #673ab7;

  &:hover {
    background-color: #7e57c2;
    border-color: #7e57c2;
  }
}

.custom-tabs .el-tabs__active-bar {
  background-color: transparent !important; /* 隐藏下划线 */
}
.custom-tabs .el-tabs__nav-wrap::after {
  position: static !important; /* 隐藏下划线 */
}
.custom-tabs .el-tabs__item.is-active {
  border: none; /* 去除选中标签的底部边框 */
  border-radius: 4px; /* 可选，为选中的标签添加圆角 */
}
.custom-tabs .el-tabs__item:not(.is-disabled):hover {
  border: none; /* 去除鼠标悬停时的底部边框 */
}

.downQna-text{
  color: #1890ff;
  margin-right: 5px;
  cursor: pointer;
}
</style>
